const fs = require('fs')
const path = require('path')
const { minimatch } = require('minimatch')

const globify = (pattern) => pattern.split('\\').join('/')

class NpmIgnore {
  constructor(ignoreFile) {
    if (!ignoreFile || !fs.existsSync(ignoreFile)) {
      this.ignoreFile = path.join(process.cwd(), '.npmignore')
    } else {
      if (fs.statSync(ignoreFile).isDirectory()) {
        this.ignoreFile = path.join(ignoreFile, '.npmignore')
      } else {
        this.ignoreFile = ignoreFile
      }
    }

    // 默认忽略的文件
    this.ignorePatterns = [
      '.*.swp',
      '._*',
      '.DS_Store',
      '.git',
      '.gitignore',
      '.hg',
      '.npmignore',
      '.npmrc',
      '.lock-wscript',
      '.svn',
      '.wafpickle-*',
      'config.gypi',
      'CVS',
      'npm-debug.log'
    ]

    if (fs.existsSync(this.ignoreFile)) {
      const content = fs.readFileSync(this.ignoreFile, 'utf-8')

      if (content === '') return

      content.split('\n').forEach((line) => {
        line = line.trim()
        if (line === '' || line.startsWith('#') || this.ignorePatterns.includes(line)) {
          return
        }
        this.ignorePatterns.push(line)
      })
    }
  }

  match(file) {
    return this.ignorePatterns.some((patterns) => minimatch(file, globify(patterns)))
  }
}

module.exports = {
  NpmIgnore
}
